package saucaca.Download;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.cmc.music.common.ID3WriteException;
import org.cmc.music.metadata.IMusicMetadata;
import org.cmc.music.metadata.MusicMetadata;
import org.cmc.music.metadata.MusicMetadataSet;
import org.cmc.music.myid3.MyID3;

import saucaca.JSON.WServiceLib;
import saucaca.Object.SongObject;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.R;


@SuppressLint("NewApi") public class DownloadTask {
	Context context;
	private DownloadManager mgr = null;
	private long lastDownload = -1L;
	String url_path = "";
	String fileName="kenhnhac";
	String songName="";
	String nameSinger="";
	SongObject songObject;
	public DownloadTask(Context context, SongObject songObject) {
		this.context = context;
		this.songObject=songObject;
		songObject.showSonginfo();
		url_path = songObject.getPATCH_FULL();
		String type=url_path.substring(url_path.length()-4, url_path.length());
		songName = songObject.getTXNAME()+type;
		if(!songName.equals("")){
			fileName=songName;
		}
		nameSinger = songObject.getNAME_SINGERS();
		mgr = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
		context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
		context.registerReceiver(onNotificationClick, new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
	}
	
	public void startDownload() {
		if(BaseEngine.isConnectionAvailable(context)){
			boolean download3G = PreferenceUtils.getBoolean(context, TagName.KeyPreference_Download3G,true);
			if (!download3G) {
				if(BaseEngine.isMobileConnected(context)){
					Toast.makeText(context, context.getResources().getString(R.string.setting_3gOff), Toast.LENGTH_SHORT).show();
				}else
					start();
			}else
				start();
		}else
				Toast.makeText(context, context.getResources().getString(R.string.error_connected), Toast.LENGTH_SHORT).show();
	}
	@SuppressLint("NewApi")
	public void start() {
		if(BaseEngine.isConnectionAvailable(context)){
			Log.e("", url_path);
			Uri uri = Uri.parse(BaseEngine.checkVideoPath(url_path));
			Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).mkdirs();
			lastDownload = mgr.enqueue(new DownloadManager.Request(uri).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
					.setAllowedOverRoaming(false).setTitle(songName)
					.setDescription(nameSinger).setDestinationInExternalPublicDir(MediaStore.Audio.Media.ARTIST, nameSinger)
					.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, fileName)
					);
			new  downloadServices().execute("");
		}
	}
	@SuppressLint("NewApi")
	public void queryStatus() {
		Cursor c = mgr.query(new DownloadManager.Query().setFilterById(lastDownload));

		if (c == null) {
			TagName.showToastShort(context, "Download not found!");
		} else {
			c.moveToFirst();

			Log.d(getClass().getName(), "COLUMN_ID: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)));
			Log.d(getClass().getName(), "COLUMN_BYTES_DOWNLOADED_SO_FAR: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)));
			Log.d(getClass().getName(), "COLUMN_LAST_MODIFIED_TIMESTAMP: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)));
			Log.d(getClass().getName(), "COLUMN_LOCAL_URI: " + c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
			Log.d(getClass().getName(), "COLUMN_STATUS: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)));
			Log.d(getClass().getName(), "COLUMN_REASON: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON)));
			TagName.showToastShort(context, statusMessage(c));
		}
	}

	//
	// public void viewLog(View v) {
	// startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
	// }

	private String statusMessage(Cursor c) {
		String msg = "???";

		switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
		case DownloadManager.STATUS_FAILED:
			msg = "Download failed!";
			break;

		case DownloadManager.STATUS_PAUSED:
			msg = "Download paused!";
			break;

		case DownloadManager.STATUS_PENDING:
			msg = "Download pending!";
			break;

		case DownloadManager.STATUS_RUNNING:
			msg = "Download in progress!";
			break;

		case DownloadManager.STATUS_SUCCESSFUL:
			msg = "Download complete!";
			break;

		default:
			msg = "Download is nowhere in sight";
			break;
		}

		return (msg);
	}

	BroadcastReceiver onComplete = new BroadcastReceiver() {
		public void onReceive(Context ctxt, Intent intent) {
			// findViewById(R.id.start).setEnabled(true);
			Bundle extras = intent.getExtras();
			DownloadManager.Query q = new DownloadManager.Query();
			q.setFilterById(extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
			Cursor c = mgr.query(q);

			if (c.moveToFirst()) {
			    int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
			    if (status == DownloadManager.STATUS_SUCCESSFUL) {
			        // process download
			        String title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
//			        queryStatus();
			    	Cursor c2 = mgr.query(new DownloadManager.Query().setFilterById(lastDownload));
			    	
					if (c2 == null) {
					} else {
						c2.moveToFirst();
						String path= c2.getString(c2.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
//						try {
							edit(path);
//						} catch (Exception e) {
//							e.printStackTrace();
//						}
//						TagName.showToastShort(context, "Đã tải: "+title);
					}
			        // get other required data by changing the constant passed to getColumnIndex
			    }
			}
			
		}
	};

	BroadcastReceiver onNotificationClick = new BroadcastReceiver() {
		public void onReceive(Context ctxt, Intent intent) {
			Toast.makeText(ctxt, "Đang tải bài hát...", Toast.LENGTH_LONG).show();
		}
	};
	
	class downloadServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String user = PreferenceUtils.getString(context, TagName.KeyPreference_user);
			if (user == null) {
				user="AppAndroid";
			}
			String str = WServiceLib.download(user, songObject.getSONG_ID());
//			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}
	}
	
	public void edit(String pathdata){
		pathdata=pathdata.replace("file://", "");
		try {
			pathdata = java.net.URLDecoder.decode(pathdata, "UTF-8");
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		 File src = new File(pathdata);
		 Log.e("", "after:\n"+pathdata);
		 
         MusicMetadataSet src_set = null;
         try {
             src_set = new MyID3().read(src);
         } catch (IOException e1) {
             e1.printStackTrace();
         } // read metadata

         if (src_set == null) // perhaps no metadata
         {
             Log.i("NULL", "NULL");
         }
         else
         {
             try{
                 IMusicMetadata metadata = src_set.getSimplified();
                 String artist = metadata.getArtist();  
                 String album = metadata.getAlbum();  
//                 String song_title = metadata.getSongTitle(); 
//                 Number track_number = metadata.getTrackNumber(); 
                 Log.i("artist", artist);
                 Log.i("album", album);
             }catch (Exception e) {
                 e.printStackTrace();
             }
             File dst = new File(pathdata);
             String str=songName.replace(".mp3", "");
             Log.e("", "name: "+str);
             Log.e("", ""+nameSinger);
             MusicMetadata meta = new MusicMetadata(str);
             meta.setAlbum("kenhnhac.vn");
             meta.setArtist(nameSinger);
             meta.setSongTitle(str);
             try {
                 new MyID3().update(src, src_set, meta);
             } catch (UnsupportedEncodingException e) {
                 e.printStackTrace();
             } catch (ID3WriteException e) {
                 e.printStackTrace();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
	}
}
